package com.century.sjt.activity.Pay;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.EMChat.activity.ChatActivity;
import com.century.sjt.EMChat.domain.EaseUser;
import com.century.sjt.EMChat.utils.EaseCommonUtils;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.activity.ShareFriendActivity;
import com.century.sjt.activity.order.MyOrderDetailsActivity;
import com.century.sjt.entity.ActionItem;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.window.MenuPopup;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by 炳基 on 2016/8/23.
 */
public class CommodityActivity extends BaseActivity {

    private SjtTitleBar titleBar;
    private WebView mWVcontent;
    private String url;
    private String ShopId,GoodId,shopName;

    private Button btn_Order;

    private String shareUrl,goodName,mainImageUrl;
    private String shopUserId,price;
    private LinearLayout layout_bottom;

    private String type;
    private ScrollView layout_scrollview;
    private MenuPopup mMenuPopup;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity);
        initView();
        initEvent();
        initData();
    }

    @Override
    protected void initView() {

        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.tab_commodit_picture));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.setRightIconResourc(getResources().getString(R.string.icon_more));
//        titleBar.setRightIconResourc(getResources().getString(R.string.icon_share));
        mWVcontent = (WebView) findViewById(R.id.news_detail_webview );
        btn_Order = (Button) findViewById(R.id.btn_place_an_order);
        layout_bottom = (LinearLayout) findViewById(R.id.layout_bottom);
        layout_scrollview = (ScrollView) findViewById(R.id.layout_scrollview);
    }

    @Override
    protected void onResume() {
//        mWVcontent.loadUrl(url);
        super.onResume();
    }

    @Override
    protected void initEvent() {
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String isMerchant = mainSharedPreferences.getString("isMerchant", "");
        String isShop = mainSharedPreferences.getString("isShop", "");
        if ("1".equals(isMerchant)||"1".equals(isShop)){
            layout_bottom.setVisibility(View.GONE);
            showMerchantMenuPopup();
        }else {
            layout_bottom.setVisibility(View.VISIBLE);
            showMenuPopup();
        }
        Intent intent=getIntent();
        url=intent.getStringExtra("url");//商品详情连接
        type = intent.getStringExtra("type");
        if ("service".equals(type)){
            layout_bottom.setVisibility(View.GONE);
        }else {
            ShopId = intent.getStringExtra("shopId");//商家ID
            GoodId = intent.getStringExtra("goodId");//商品ID
            shareUrl = intent.getStringExtra("shareUrl");//分享链接
            goodName = intent.getStringExtra("goodName");//商品名称
            mainImageUrl = intent.getStringExtra("mainImageUrl");//商品主图
            shopUserId = intent.getStringExtra("shopUserId");//商家用户ID
            price = intent.getStringExtra("price");//商品单价
            shopName = intent.getStringExtra("shopName");
        }
        WebSettings settings = mWVcontent.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        btn_Order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                placeAnOrder();
            }
        });
        mWVcontent.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){

                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:
                        layout_scrollview.requestDisallowInterceptTouchEvent(false);
                        break;
                    case MotionEvent.ACTION_UP:
                        layout_scrollview.requestDisallowInterceptTouchEvent(true);
                        break;
                }
                return false;
            }
        });



        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                showShare();
                mMenuPopup.show(view);
            }
        });

    }

    @Override
    protected void initData() {

        mWVcontent.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });
        mWVcontent.loadUrl(url);
    }

    //下单
    private void placeAnOrder() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), CommodityActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.createMyOrderHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        JSONObject data = res.getJSONObject("data");
                        String orderId = data.getString("orderid");
                        if (!(orderId.equals("null"))){
                            Intent intent = new Intent(CommodityActivity.this, MyOrderDetailsActivity.class);
                            intent.putExtra("orderId", orderId);
                            intent.putExtra("falg",1);
                            startActivity(intent);
                        }else{
                            TipUtil.showToast(getResources().getString(R.string.text_please_choose_goods), CommodityActivity.this, 1);
                        }
                    } else {
                        TipUtil.showToast(message, CommodityActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), CommodityActivity.this, 1);
                }
                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), CommodityActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("shopId", ShopId);//分店id
                map.put("goodId", GoodId);//商品id
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    public void showShare() {

        ShareSDK.initSDK(CommodityActivity.this);
        OnekeyShare oks = new OnekeyShare();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitleUrl(shareUrl);
        oks.setTitle(goodName);
//        String loginid=SjtMainActivity.mainSharePreferences.getString("loginid","");
//        oks.setImagePath(Constant.CAMERA_PICTURE_PATH + loginid);
        oks.setImageUrl(mainImageUrl);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(goodName);
//        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        oks.setUrl(shareUrl);
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(getString(R.string.app_name));
        oks.show(CommodityActivity.this);
    }

    //发送消息方法
    //==========================================================================
    protected void sendTextMessage(String content) {
        EMMessage message = EMMessage.createTxtSendMessage(content, shopUserId);
        message.setAttribute("ext_type","2");
        message.setAttribute("price",price);
        message.setAttribute("shopId",ShopId);
        message.setAttribute("goodId",GoodId);
        message.setAttribute("mainImageUrl",mainImageUrl);
        message.setAttribute("detailsUrl",url);
        message.setAttribute("goodName",goodName);
        message.setAttribute("shareUrl",shareUrl);
        EMChatManager.getInstance().sendMessage(message, null);
    }


    private void AddShop(final String friendId) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), CommodityActivity.this);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.addFriendIsShop, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject Data= res.getJSONObject("data");
                    if (code.equals("200")) {//成功
                        JSONObject aData = Data.getJSONObject("friendShop");
                        String userId = aData.getString("userId");
                        String nick = aData.getString("nickName");
                        String initialLetter = aData.getString("initialLetter");
                        String mobile = aData.getString("mobile");
                        String imageId = aData.getString("imageId");
                        String imageUrl = aData.getString("imageUrl");
                        String Shopid = aData.getString("shopId");
                        EaseUser user = new EaseUser(userId);
                        user.setNick(nick);
                        user.setMobile(mobile);
                        user.setInitialLetter(initialLetter);
                        user.setAvatarid(imageId);
                        user.setAvatar(imageUrl);
                        user.setShopId(Shopid);
                        user.setIsShop("1");
                        EaseCommonUtils.setUserInitialLetter(user);
                        SjtHelper.getInstance().updateUser(user);
                        sendTextMessage(goodName);
                        startActivity(new Intent(CommodityActivity.this, ChatActivity.class).putExtra("userId",friendId));

                    } else {//失败
                        new AlertDialog.Builder(CommodityActivity.this)
                                .setMessage(message)
                                .setTitle(getResources().getString(R.string.text_prompt))
                                .setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .show();
//                        TipUtil.showToast(message, MerchantItemActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), CommodityActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), CommodityActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("userId", userId);
                map.put("friendId",friendId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }
    private void showMenuPopup(){
        mMenuPopup = new MenuPopup(this, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mMenuPopup.addAction(new ActionItem(this, getResources().getString(R.string.text_goto_shop), getResources().getString(R.string.icon_store)));
        mMenuPopup.addAction(new ActionItem(this, getResources().getString(R.string.text_recommend_goods), getResources().getString(R.string.icon_shopping)));
        mMenuPopup.addAction(new ActionItem(this, getResources().getString(R.string.text_consultation_goods), getResources().getString(R.string.icon_news)));
        mMenuPopup.addAction(new ActionItem(this, getResources().getString(R.string.text_share), getResources().getString(R.string.icon_share)));
        mMenuPopup.setItemOnClickListener(new MenuPopup.OnItemOnClickListener() {
            @Override
            public void onItemClick(ActionItem item, int position) {

                switch (position) {
                    case 0:
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.setClass(CommodityActivity.this, CommodityListActivity.class);
                        intent.putExtra("shopId",ShopId);
                        intent.putExtra("shopName",shopName);
                        startActivity(intent);
                        break;
                    case 1:
                        Intent intent1 = new Intent();
                        intent1.setClass(CommodityActivity.this, ShareFriendActivity.class);
                        intent1.putExtra("url",url);
                        intent1.putExtra("shopId",ShopId);
                        intent1.putExtra("goodId",GoodId);
                        intent1.putExtra("shareUrl",shareUrl);
                        intent1.putExtra("goodName",goodName);
                        intent1.putExtra("mainImageUrl",mainImageUrl);
                        intent1.putExtra("shopUserId",shopUserId);
                        intent1.putExtra("price",price);
                        intent1.putExtra("type","goods");
                        intent1.putExtra("shopName",shopName);
                        startActivity(intent1);
                        break;
                    case 2:
                        if (SjtHelper.getInstance().getContactList().get(shopUserId)==null){
                            AddShop(shopUserId);
                        }else {
                            sendTextMessage(goodName);
                            startActivity(new Intent(CommodityActivity.this, ChatActivity.class).putExtra("userId",shopUserId));
                        }
                        break;
                    case 3:
                        showShare();
                        break;

                }

            }
        });
    }
    private void showMerchantMenuPopup(){
        mMenuPopup = new MenuPopup(this, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mMenuPopup.addAction(new ActionItem(this, getResources().getString(R.string.text_goto_shop), getResources().getString(R.string.icon_store)));
        mMenuPopup.addAction(new ActionItem(this, getResources().getString(R.string.text_recommend_goods), getResources().getString(R.string.icon_shopping)));
        mMenuPopup.addAction(new ActionItem(this, getResources().getString(R.string.text_share), getResources().getString(R.string.icon_share)));
        mMenuPopup.setItemOnClickListener(new MenuPopup.OnItemOnClickListener() {
            @Override
            public void onItemClick(ActionItem item, int position) {

                switch (position) {
                    case 0:
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.setClass(CommodityActivity.this, CommodityListActivity.class);
                        intent.putExtra("shopId",ShopId);
                        intent.putExtra("shopName",shopName);
                        startActivity(intent);
                        break;
                    case 1:
                        Intent intent1 = new Intent();
                        intent1.setClass(CommodityActivity.this, ShareFriendActivity.class);
                        intent1.putExtra("url",url);
                        intent1.putExtra("shopId",ShopId);
                        intent1.putExtra("goodId",GoodId);
                        intent1.putExtra("shareUrl",shareUrl);
                        intent1.putExtra("goodName",goodName);
                        intent1.putExtra("mainImageUrl",mainImageUrl);
                        intent1.putExtra("shopUserId",shopUserId);
                        intent1.putExtra("price",price);
                        intent1.putExtra("type","goods");
                        startActivity(intent1);
                        break;
                    case 2:
                        showShare();
                        break;

                }

            }
        });
    }
}
